/*
package cn.szzsi._web;

import cn.szzsi._Config;
import cn.szzsi.common.bean.SystemConfig.StoreFreezeTime;
import cn.szzsi.common.bean.WeixinConfig;
import cn.szzsi.common.bean.dto.AjaxResult;
import cn.szzsi.common.bean.dto.PayAttach;
import cn.szzsi.common.cfg.AlipayConfig;
import cn.szzsi.common.exception.BusinessException;
import cn.szzsi.common.kit.AlipayNotify;
import cn.szzsi.common.kit.CommonUtil;
import cn.szzsi.common.kit.IdGen;
import cn.szzsi.common.kit.SerialNumberUtil;
import cn.szzsi.common.model.*;
import cn.szzsi.common.model.OrderLog.OrderLogType;
import cn.szzsi.common.model.Payment.PaymentStatus;
import cn.szzsi.common.model.Payment.PaymentType;
import cn.szzsi.service.*;
import com.jfinal.aop.Before;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.api.*;
import com.jfinal.weixin.sdk.kit.IpKit;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.weixin.sdk.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;


*/
/**
 * 前台类 - 支付处理
 *
 *//*

public class PaymentController_bak extends BaseWebController<Payment> {

	// 支付结果（成功、失败）
	public enum PaymentResult {
		success, failure
	}

	private PaymentType paymentType;// 支付类型
	private BigDecimal amountPayable;// 应付金额（不含支付费用）
	private BigDecimal paymentFee;// 支付手续费
	private PaymentResult paymentResult;// 支付结果
	private PaymentConfig paymentConfig;// 支付方式
	private Orders order;// 订单
	private String path;//模板路径
	private String uid;//商户id,也是用户的店铺id
	private String shopId;//店铺id
	private String customerType;
	//static Log log=Log.getLog(WeixinApiController.class);
	private AjaxResult ajax = new AjaxResult();//微信支付返回状态
	//商户相关资料
	private String appid;//应用ID
	private String secret;//应用密钥
	private String partner;//商户号
	private String key;//支付秘钥

	private String notify_url = ""+ _Config.p.get("mall_web.url")+"/b/payment/wxNotice";//回调接口

	// 支付确认
	public void confirm() {
		uid=getLoginMember().getStr("shopId");
		amountPayable = new BigDecimal(getPara("amountPayable","0"));
		paymentType = PaymentType.valueOf(getPara("paymentType"));
		String paymentConfigId = getPara("paymentConfig.id","");
		String orderId = getPara("order.id");
		if (paymentType == PaymentType.recharge) {
			if (amountPayable == null) {
				addActionError("请输入充值金额！");
				return;
			}
			if (amountPayable.compareTo(new BigDecimal("0")) <= 0) {
				addActionError("充值金额必须大于0！");
				return;
			}
			if (amountPayable.scale() > getSystemConfig().getOrderScale()) {
				addActionError("充值金额小数位超出限制！");
				return;
			}
			if (StringUtils.isEmpty(paymentConfigId)) {
				addActionError("请选择支付方式！");
				return;
			}
			if (StrKit.notBlank(paymentConfigId)){
				paymentConfig = PaymentConfig.dao.findById(paymentConfigId);
			}
			paymentFee = paymentConfig.getPaymentFee(amountPayable);
		} else {
			if (StringUtils.isEmpty(orderId)) {
				addActionError("订单信息错误！");
				return;
			}
			order = Orders.dao.findById(orderId);
			paymentConfig = order.getPaymentConfig();
			paymentFee = order.getBigDecimal("paymentFee");
			amountPayable = order.getBigDecimal("totalAmount").subtract(paymentFee).subtract(order.getBigDecimal("paidAmount"));
			if(paymentConfig.getPaymentConfigTypeValue() == PaymentConfig.PaymentConfigType.weixin){//微信支付
				appid=_Config.p.get("wechat_appid");
				secret=_Config.p.get("wechat_secret");
				WeixinConfig weixinConfig=new WeixinConfig();
				weixinConfig.setAppid(appid);
				weixinConfig.setSecret(secret);
				ApiConfigKit.setThreadLocalApiConfig(getApiConfig(weixinConfig));

				JsTicket jsApiTicket = JsTicketApi.getTicket(JsTicketApi.JsApiType.jsapi);
				String jsapi_ticket = jsApiTicket.getTicket();
				String nonce_str = create_nonce_str();
				// 注意 URL 一定要动态获取，不能 hardcode.
				String url=""+ _Config.p.get("mall_web.url")+""
						+getRequest().getServletPath();
				String qs = getRequest().getQueryString(); // 参数
				if (qs != null) {
					url = url + "?" + (getRequest().getQueryString());
				}
				String timestamp = create_timestamp();
				// 这里参数的顺序要按照 key 值 ASCII 码升序排序
				//注意这里参数名必须全部小写，且必须有序
				String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
				String signature = HashKit.sha1(str);
				setAttr("appId", ApiConfigKit.getApiConfig().getAppId());
				setAttr("nonceStr", nonce_str);
				setAttr("timestamp", timestamp);
				setAttr("url", url);
				setAttr("signature", signature);
				setAttr("base", getRequest().getContextPath());
				setAttr("jsapi_ticket", jsapi_ticket);
				setAttr("openId",getLoginMember().getStr("openid"));

			}

		}
		setAttr("order", order);
		setAttr("paymentType", paymentType);
		setAttr("amountPayable", amountPayable);
		setAttr("paymentFee", paymentFee);
		setAttr("paymentConfig", paymentConfig);
		if(CommonUtil.isMobileDevice(getRequest())){
			wapTemplatePath("payment_confirm.html");
		}else{
			pcTemplatePath("payment_confirm.html");
		}

	}

	// 支付入口
	@Before(Tx.class)
	public void gateway() {
		String orderId = getPara("order.id","");
		String paymentConfigId = getPara("paymentConfig.id","");
		amountPayable = new BigDecimal(getPara("amountPayable","0"));
		String pt = getPara("paymentType","");
		final Member loginMember = getLoginMember();
		shopId=loginMember.getStr("shopId");
		setAttr("shopId",shopId);

		if (StrKit.notBlank(pt)){
			paymentType = PaymentType.valueOf(pt);
		}
		if (paymentType == PaymentType.deposit) {
			if (StringUtils.isEmpty(orderId)) {
				addActionError("订单信息错误！");
				return;
			}
			order = Orders.dao.findById(orderId);
			paymentConfig = order.getPaymentConfig();
			if (paymentConfig.getPaymentConfigTypeValue() != PaymentConfig.PaymentConfigType.deposit) {
				addActionError("支付方式错误！");
				return;
			}
			if (order.getOrderStatusValue() == Orders.OrderStatus.completed || order.getOrderStatusValue() == Orders.OrderStatus.invalid) {
				addActionError("订单状态错误！");
				return;
			}
			if (order.getPaymentStatusValue() == Orders.PaymentStatus.paid) {
				addActionError("订单付款状态错误！");
				return;
			}
			if (UserBalance.dao.findByMemberId(getLoginMember().getStr("id")).getBigDecimal("balance").compareTo(order.getBigDecimal("totalAmount").subtract(order.getBigDecimal("paidAmount"))) < 0) {
				paymentResult = PaymentResult.failure;
				setAttr("paymentResult",paymentResult);
				setAttr("loginMember",loginMember);
				render(CommonUtil.TEMPLATE_PATH+"/platform/web/payment_deposit_result.html");
				return;
			}
			paymentFee = order.getBigDecimal("paymentFee");
			amountPayable = order.getBigDecimal("totalAmount").subtract(paymentFee).subtract(order.getBigDecimal("paidAmount"));
		} else if (paymentType == PaymentType.point) {
			if (StringUtils.isEmpty(orderId)) {
				addActionError("订单信息错误！");
				return;
			}
			order = Orders.dao.findById(orderId);
			paymentConfig = order.getPaymentConfig();
			if (paymentConfig.getPaymentConfigTypeValue() != PaymentConfig.PaymentConfigType.point) {
				addActionError("支付方式错误！");
				return;
			}
			if (order.getOrderStatusValue() == Orders.OrderStatus.completed || order.getOrderStatusValue() == Orders.OrderStatus.invalid) {
				addActionError("订单状态错误！");
				return;
			}
			if (order.getPaymentStatusValue() == Orders.PaymentStatus.paid) {
				addActionError("订单付款状态错误！");
				return;
			}
			if (new BigDecimal(UserBalance.dao.findByMemberId(getLoginMember().getStr("id")).getInt("point")).compareTo(order.getBigDecimal("totalAmount").subtract(order.getBigDecimal("paidAmount"))) < 0) {
				paymentResult = PaymentResult.failure;
				setAttr("paymentResult",paymentResult);
				setAttr("loginMember",loginMember);
				render(CommonUtil.TEMPLATE_PATH+"/platform/web/payment_point_result.html");
				return;
			}
			paymentFee = order.getBigDecimal("paymentFee");
			amountPayable = order.getBigDecimal("totalAmount").subtract(paymentFee).subtract(order.getBigDecimal("paidAmount"));
		} else if (paymentType == PaymentType.online||paymentType == PaymentType.weixin || paymentType== PaymentType.alipay) {
			if (StringUtils.isEmpty(orderId)) {
				addActionError("订单信息错误！");
				return;
			}
			order = Orders.dao.findById(orderId);
			paymentConfig = order.getPaymentConfig();
			paymentFee = order.getBigDecimal("paymentFee");
			amountPayable = order.getBigDecimal("totalAmount").subtract(paymentFee).subtract(order.getPaidAmount());
		}
		BigDecimal totalAmount = amountPayable.add(paymentFee);// 总金额
		if (paymentConfig.getPaymentConfigTypeValue() == PaymentConfig.PaymentConfigType.deposit||paymentConfig.getPaymentConfigTypeValue() == PaymentConfig.PaymentConfigType.point) {//积分或者余额支付
			if (totalAmount.compareTo(order.getBigDecimal("totalAmount").subtract(order.getBigDecimal("paidAmount"))) == 0) {
				order.set("paymentStatus", Orders.PaymentStatus.paid.ordinal());
				order.set("paidAmount",order.getBigDecimal("paidAmount").add(totalAmount));
			} else if (totalAmount.compareTo(order.getBigDecimal("totalAmount")) < 0) {
				order.set("paymentStatus", Orders.PaymentStatus.partPayment.ordinal());
				order.set("paidAmount",order.getBigDecimal("paidAmount").add(totalAmount));
			} else {
				addActionError("交易金额错误！");
				return;
			}
			order.update();

			if(paymentConfig.getPaymentConfigTypeValue() == PaymentConfig.PaymentConfigType.deposit){//预存款支付
				UserBalanceService.service.updateBalance(loginMember,totalAmount.multiply(new BigDecimal(-1)));//更新会员余额结果
				//支付明细
				UserBalanceDetailService.service.savePaymentInfo(loginMember.getId(),order.getTotalAmount(),UserBalanceDetail.BalanceType.memberPayment.ordinal(),order.getUid(),order.getOrderSn());
			}else if(paymentConfig.getPaymentConfigTypeValue() == PaymentConfig.PaymentConfigType.point){//积分支付
				UserBalanceService.service.updatePoint(loginMember,-totalAmount.intValue());//更新会员余额结果,待改进,四舍五入问题
				//积分明细
				UserPointDetailService.service.saveInfo(loginMember.getStr("id"),totalAmount.intValue(), UserPointDetail.PointDetailType.memberPayment.ordinal(),"订单支付");

			}
			//保存支付信息
			PaymentService.service.savePayment(paymentType.ordinal(),paymentConfig.getName(),totalAmount,paymentFee,loginMember.getUsername(), PaymentStatus.success.ordinal(),paymentConfigId,order.getId(), SerialNumberUtil.buildPaymentSn(),shopId);

			//会员支付完毕,更新会员等级,放到线程里面跑
			_Config.fixedThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					try {//执行分销处理
						FenxiaoService.service.fenxiaoHandle(amountPayable,loginMember,orderP);
					} catch (BusinessException e) {
						e.printStackTrace();
					}

				}
			});

			// 库存处理
			if (getSystemConfig().getStoreFreezeTime() == StoreFreezeTime.payment) {
				for (OrderItem orderItem : order.getOrderItemList()) {
					Product product = orderItem.getProduct();
					if (product.getInt("store") != null) {
						product.set("freezeStore",product.getInt("freezeStore") + orderItem.getInt("productQuantity"));
						if (product.getIsOutOfStock()) {
							orderItem.getProduct().getProductAttributeMapStore();
						}
						product.update();
						if (product.getIsOutOfStock()) {
							HtmlService.service.productContentBuildHtml(product);
						}
					}
				}
			}

			// 订单日志
			PaymentService.service.saveOrderLog(OrderLogType.payment.ordinal(),order,paymentConfig,totalAmount);
			setAttr("paymentResult", PaymentResult.success);
			setAttr("amountPayable",amountPayable);
			setAttr("paymentFee",paymentFee);

			redirect("/b/order/view?shopId="+order.getUid()+"&id="+order.getId());
			return;
		} else if(paymentConfig.getPaymentConfigTypeValue() == PaymentConfig.PaymentConfigType.alipay){//支付宝支付
			//保存支付信息
			PaymentService.service.savePayment(paymentType.ordinal(),paymentConfig.getStr("name"),totalAmount,paymentFee,getLoginMember().getStr("username"), PaymentStatus.ready.ordinal(),paymentConfigId,order.getStr("id"), SerialNumberUtil.buildPaymentSn(),shopId);

			//给支付宝接口发送请求参数
			//将商户的支付宝合作身份者ID和MD5密钥赋值给支付宝即时到账即参数
			String partner= _Config.p.get("alipay_bargainorId");
			String key= _Config.p.get("alipay_key");
			AlipayConfig alipayConfig=new AlipayConfig();
			alipayConfig.setPartner(partner);
			alipayConfig.setKey(key);
			PrintWriter out= null;
			try {
				getResponse().setContentType("text/html;charset=utf-8");
				out = getResponse().getWriter();
			} catch (IOException e) {
				e.printStackTrace();
			}
			//订单号:orderId
			//String orderSn=order.getStr("orderSn");//
			//商品名称
			String subject=order.getStr("orderSn");
			//付款金额
			DecimalFormat df = new DecimalFormat("0.00"); // 保留几位小数
			String totalFee=df.format(totalAmount);
			//商品描述

			StringBuffer sbHtml = new StringBuffer();
			//<form id="alipaysubmit" name="alipaysubmit" action="https://mapi.alipay.com/gateway.do?_input_charset=utf-8" method="get">
			sbHtml.append("<form id=\"alipayform\" action=\"/html/alipayapi.jsp?_input_charset= \""+ AlipayConfig.input_charset + "\" method=\"POST\">");
			sbHtml.append("<input type=\"hidden\" name=\"WIDout_trade_no\" value=\"" + orderId + "\"/>");//订单编号
			sbHtml.append("<input type=\"hidden\" name=\"WIDsubject\" value=\"" + subject + "\"/>");//商品名称
			sbHtml.append("<input type=\"hidden\" name=\"WIDtotal_fee\" value=\"" + totalFee + "\"/>");//付款金额
			sbHtml.append("<input type=\"hidden\" name=\"WIDbody\" value=\"" + totalFee + "\"/>");//商品描述
			sbHtml.append("<script>document.forms['alipayform'].submit();</script>");
			out.println(sbHtml.toString());
			renderNull();

		}else if (paymentConfig.getPaymentConfigTypeValue() == PaymentConfig.PaymentConfigType.weixin) {//微信支付
			System.out.println("----------------------微信支付开始");
			PaymentService.service.savePayment(paymentType.ordinal(),paymentConfig.getStr("name"),totalAmount,paymentFee,getLoginMember().getStr("username"), PaymentStatus.ready.ordinal(),paymentConfigId,order.getStr("id"), SerialNumberUtil.buildPaymentSn(),shopId);

			String productId = getPara("productId","");
			Product product = Product.dao.findById(productId);
			appid=_Config.p.get("wechat_appid");
			secret=_Config.p.get("wechat_secret");
			partner= _Config.p.get("weichat_bargainorId");
			key=_Config.p.get("weichat_key");
			// openId，采用 网页授权获取 access_token API：SnsAccessTokenApi获取
			String openId=getPara("openId");
			String total_fee=getPara("total_fee");
			if(StrKit.isBlank(total_fee)){
				total_fee = paymentFee.toString();
			}

			// 统一下单文档地址：https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1

			Map<String, String> params = new HashMap<String, String>();
			params.put("appid", appid);//AppID(应用ID)
			params.put("mch_id", partner);//商户号
			if(product != null)
				params.put("body", product.getStr("name"));
			else
				params.put("body", "微信商城产品在线交易");

//			String out_trade_no=System.currentTimeMillis()+"";//商户订单号.待改进
			String out_trade_no=order.getStr("orderSn")+"_"+ IdGen.get().nextId(12);//商户订单号
			params.put("out_trade_no", out_trade_no);
			int price=((int)(Float.valueOf(total_fee)*100));
			params.put("total_fee", price+"");
			params.put("attach", JsonKit.toJson(new PayAttach(out_trade_no, 2, 3)));
			String ip = IpKit.getRealIp(getRequest());
			if (StrKit.isBlank(ip)) {
				ip = "127.0.0.1";
			}

			params.put("spbill_create_ip", ip);
			params.put("trade_type", PaymentApi.TradeType.JSAPI.name());
			params.put("nonce_str", System.currentTimeMillis() / 1000 + "");
			params.put("notify_url", notify_url);
			params.put("openid", openId);

			String sign = PaymentKit.createSign(params, key);//支付秘钥
			params.put("sign", sign);
			String xmlResult = PaymentApi.pushOrder(params);

			Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
			String return_code = result.get("return_code");
			String return_msg = result.get("return_msg");
			if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
				ajax.addError(return_msg);
				renderJson(ajax);
				return;
			}

			// 以下字段在return_code 和result_code都为SUCCESS的时候有返回
			String prepay_id = result.get("prepay_id");
			Map<String, String> packageParams = new HashMap<String, String>();
			packageParams.put("appId", appid);
			packageParams.put("timeStamp", System.currentTimeMillis() / 1000 + "");
			packageParams.put("nonceStr", System.currentTimeMillis() + "");
			packageParams.put("package", "prepay_id=" + prepay_id);
			packageParams.put("signType", "MD5");
			String packageSign = PaymentKit.createSign(packageParams, key);
			packageParams.put("paySign", packageSign);
			String jsonStr = JsonUtils.toJson(packageParams);
			System.out.println("jsonStr--------"+jsonStr);
			ajax.success(jsonStr);
			renderJson(ajax);
		}

	}

	//支付宝服务器异步通知页面
	public void alipayNotice(){
		System.out.println("-----------------付宝服务器异步通知页面");
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = getRequest().getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		//商户订单号
		String out_trade_no = new String(getPara("out_trade_no"));
		//支付宝交易号
		String trade_no = new String(getPara("trade_no"));
		//交易状态
		String trade_status = new String(getPara("trade_status"));
		//交易金额
		String total_fee= new String(getPara("total_fee"));
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		PrintWriter out= null;
		try {
			getResponse().setContentType("text/html;charset=utf-8");
			out = getResponse().getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}

		if(AlipayNotify.verify(params)){//验证成功
			//请在这里加上商户的业务逻辑程序代码
			Payment payment = null;
			payment = Payment.dao.getPaymentByOrderId(out_trade_no);
			if (payment == null) {
				addActionError("支付信息错误！");
				return;
			}
			if (payment.getPaymentStatusValue() == PaymentStatus.success) {
				addActionError("此交易已经完成支付，请勿重复提交！");
				return;
			}
			if (payment.getPaymentStatusValue() != PaymentStatus.ready) {
				addActionError("交易状态错误！");
				return;
			}
			BigDecimal totalAmount = new BigDecimal(total_fee);// 支付总金额
			if (totalAmount.compareTo(payment.getBigDecimal("totalAmount")) != 0) {
				addActionError("交易金额错误！");
				return;
			}
			amountPayable = totalAmount.subtract(payment.getBigDecimal("paymentFee"));// 应付金额（不含支付费用）
			paymentFee = payment.getBigDecimal("paymentFee");
			if (payment.getPaymentTypeValue() == PaymentType.alipay) {
				order = payment.getOrder();
				if (totalAmount.compareTo(order.getBigDecimal("totalAmount").subtract(order.getBigDecimal("paidAmount"))) == 0) {
					order.set("paymentStatus", Orders.PaymentStatus.paid.ordinal());
					order.set("paidAmount",order.getBigDecimal("paidAmount").add(totalAmount));
				} else if (totalAmount.compareTo(order.getBigDecimal("totalAmount")) < 0) {
					order.set("paymentStatus", Orders.PaymentStatus.partPayment);
					order.set("paidAmount",order.getBigDecimal("paidAmount").add(totalAmount));
				} else {
					addActionError("交易金额错误！");
					return;
				}
				order.set("trade_no",trade_no);
				order.update();

				final Member loginMember = Member.dao.findById(order.getMemberId());
				//会员支付完毕,更新会员等级,放到线程里面跑
				_Config.fixedThreadPool.execute(new Runnable() {
					@Override
					public void run() {
						//1.更改会员等级
						MemberRankService.service.updateMemberRank(loginMember);
						//2.执行分销判断和处理开始
						//(1)，判断该商户是否开通分销
						//(2)，向上级返佣金
						SiteConfig sc = SiteConfig.dao.findByShopId(shopId);
						if(sc.getInt("openFenxiao") == 1){
							//执行分销处理
							try {
								FenxiaoService.service.fenxiaoHandle(amountPayable,loginMember,order);
							} catch (BusinessException e) {
								e.printStackTrace();
							}
						}
					}
				});

				// 订单日志
				PaymentService.service.saveOrderLog(OrderLogType.payment.ordinal(),order,paymentConfig,payment.getBigDecimal("totalAmount"));

				//支付宝支付添加到资金明细
				UserBalanceDetailService.service.savePaymentInfo(order.getMemberId(),order.getBigDecimal("totalAmount"), UserBalanceDetail.BalanceType.memberPayment.ordinal(),order.getUid(),order.getStr("orderSn"));
			} else {
				addActionError("交易类型错误！");
				return;
			}
			payment.set("paymentStatus", PaymentStatus.success.ordinal());
			payment.update();
			out.print("success");	//请不要修改或删除
			System.out.println("**************************用户支付成功*****************");
			renderNull();
		}else{//验证失败
			System.out.println("*********************fail*********************");
			out.print("fail");
		}
	}

	//支付宝页面跳转同步通知页面
	public void alipayReturn(){
		System.out.println("---------------------支付宝页面跳转同步通知页面");
		//获取支付宝GET过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = getRequest().getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		//商户订单号
		String out_trade_no = new String(getPara("out_trade_no"));

		//支付宝交易号
		String trade_no = new String(getPara("trade_no"));

		//交易状态
		String trade_status = new String(getPara("trade_status"));

		//交易金额
		String total_fee= new String(getPara("total_fee"));

		//用户类型
		customerType="0";
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

		//计算得出通知验证结果
		boolean verify_result = AlipayNotify.verify(params);
		PrintWriter out= null;
		try {
			getResponse().setContentType("text/html;charset=utf-8");
			out = getResponse().getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(verify_result){//验证成功

			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
				//判断该笔订单是否在商户网站中已经做过处理
				//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				//如果有做过处理，不执行商户的业务程序
			}
			//该页面可做页面美工编辑
			order= Orders.dao.getOrderByTransactionId(trade_no);
			if("0".equals(customerType)){//商户用户
				redirect("/b/order/view?id="+out_trade_no+"&shopId="+order.getUid());//跳转到订单详情页
			}else{//平台用户
				redirect("/shop/order/view?id="+out_trade_no+"&shopId="+order.getUid());//跳转到订单详情页
			}
			//redirect("/b/order/view?id="+out_trade_no+"");//跳转到订单详情页

			//out.println("验证成功<br />");
			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

		}else{
			System.out.println("******验证失败");
			//该页面可做页面美工编辑
			out.println("验证失败");
		}
	}

	//微信支付结果请求处理
	public void wxNotice() {
		//获取所有的参数
		StringBuffer sbf=new StringBuffer();
		Enumeration<String> en=getParaNames();
		while (en.hasMoreElements()) {
			Object o= en.nextElement();
			sbf.append(o.toString()+"="+getPara(o.toString()));
		}

		//log.error("支付通知参数："+sbf.toString());

		// 支付结果通用通知文档: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7
		String xmlMsg = HttpKit.readIncommingRequestData(getRequest());
		System.out.println("支付通知="+xmlMsg);
		Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);

		String appid  = params.get("appid");

		//商户号
		String mch_id  = params.get("mch_id");
		String result_code  = params.get("result_code");
		String openId      = params.get("openid");
		//交易类型
		String trade_type      = params.get("trade_type");
		//付款银行
		String bank_type      = params.get("bank_type");
		// 总金额
		String total_fee     = params.get("total_fee");
		//现金支付金额
		String cash_fee     = params.get("cash_fee");
		// 微信支付订单号
		String trade_no      = params.get("transaction_id");
		// 商户订单号
		String out_trade_no      = params.get("out_trade_no");
		// 支付完成时间，格式为yyyyMMddHHmmss
		String time_end      = params.get("time_end");

		/////////////////////////////以下是附加参数///////////////////////////////////

		String attach = params.get("attach");
		String fee_type= params.get("fee_type");
		String is_subscribe= params.get("is_subscribe");
		String err_code= params.get("err_code");
		String err_code_des= params.get("err_code_des");

		PrintWriter out= null;
		try {
			getResponse().setContentType("text/html;charset=utf-8");
			out = getResponse().getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
		// 避免已经成功、关闭、退款的订单被再次更新
		Orders order_out = Orders.dao.getOrderByTransactionId(trade_no);
		if (order_out==null) {
			//获取key
			String temp = out_trade_no;
			if(out_trade_no.contains("_"))
				temp = out_trade_no.split("_")[0];
			System.out.println("商户订单号(orderSn)--------------"+temp);
			order = Orders.dao.getOrderBySN(temp);
			key=_Config.p.get("alipay_key");
			if(PaymentKit.verifyNotify(params, key)){
				if (("SUCCESS").equals(result_code)) {
					//更新订单信息,请在这里加上商户的业务逻辑程序代码
					Payment payment = null;
					payment = Payment.dao.getPaymentByOrderId(order.getStr("id"));
					if (payment == null) {
                        System.out.println("支付信息错误！");
                        return;
					}
					if (payment.getPaymentStatusValue() == PaymentStatus.success) {
                        System.out.println("此交易已经完成支付，请勿重复提交！");
						return;
					}
					if (payment.getPaymentStatusValue() != PaymentStatus.ready) {
                        System.out.println("交易状态错误！");
						return;
					}
					BigDecimal totalAmount = new BigDecimal(Double.valueOf(total_fee)/100);// 支付总金额
					DecimalFormat df = new DecimalFormat("0.00"); // 保留几位小数
					String totalFee=df.format(new BigDecimal(Double.valueOf(total_fee)/100));
					totalAmount=new BigDecimal(totalFee);
					if (totalAmount.compareTo(payment.getBigDecimal("totalAmount")) != 0) {
						addActionError("交易金额错误！");
						return;
					}
					amountPayable = totalAmount.subtract(payment.getBigDecimal("paymentFee"));// 应付金额（不含支付费用）
					paymentFee = payment.getBigDecimal("paymentFee");
					if (totalAmount.compareTo(order.getBigDecimal("totalAmount").subtract(order.getBigDecimal("paidAmount"))) == 0) {
						System.out.println("&&&&&&&&&&&&&&&&&&&&&&&99");
						order.set("paymentStatus", Orders.PaymentStatus.paid.ordinal());
						order.set("paidAmount",order.getBigDecimal("paidAmount").add(totalAmount));
					} else if (totalAmount.compareTo(order.getBigDecimal("totalAmount")) < 0) {
						System.out.println("&&&&&&&&&&&&&&&&&&&&&&&99000");
						order.set("paymentStatus", Orders.PaymentStatus.partPayment);
						order.set("paidAmount",order.getBigDecimal("paidAmount").add(totalAmount));
					} else {
						addActionError("交易金额错误！");
						return;
					}
					order.set("trade_no",trade_no);
					order.update();
					//库存处理############
					// 订单日志
					PaymentService.service.saveOrderLog(OrderLogType.payment.ordinal(),order,paymentConfig,payment.getBigDecimal("totalAmount"));
					payment.set("paymentStatus", PaymentStatus.success.ordinal());
					payment.update();
					final Member loginMember = Member.dao.findById(order.getMemberId());
					//会员支付完毕,更新会员等级,放到线程里面跑
					_Config.fixedThreadPool.execute(new Runnable() {
						@Override
						public void run() {
								try {
									//ApiConfigKit.setThreadLocalApiConfig(SessionUtil.getApiConfig(siteConfig.getApiid()));
									//更新冻结金额开始
									UserBalance userBalance= UserBalance.dao.findByMemberId(order.getStr("member_id"));
									userBalance.set("freezeMoney", 0.00).update();
									//更新冻结金额结束
									FenxiaoService.service.fenxiaoHandle(amountPayable,loginMember,order);
									//ApiConfigKit.removeThreadLocalApiConfig();
								} catch (BusinessException e) {
									e.printStackTrace();
								}

						}
					});
					//微信支付成功后添加到资金明细(b_user_balance_detail)
					UserBalanceDetailService.service.savePaymentInfo(order.getMemberId(),order.getTotalAmount(), UserBalanceDetail.BalanceType.memberPayment.ordinal(),order.getUid(),order.getOrderSn());
					//发送通知等
					Map<String, String> xml = new HashMap<String, String>();
					xml.put("return_code", "SUCCESS");
					xml.put("return_msg", "OK");
					out.print(PaymentKit.toXml(xml));
					//renderText(PaymentKit.toXml(xml).toString());
					System.out.println("**********************订单支付成功");
					renderNull();
					return;
				}
			}
		}
		System.out.println("**********************微信交易结束结束");
		renderNull();
	}


	public ApiConfig getApiConfig(WeixinConfig weixinConfig) {
		ApiConfig ac = new ApiConfig();
		// 配置微信 API 相关常量
		//ac.setToken(AConfig.p.get("token"));
		ac.setAppId(weixinConfig.getAppid());
		ac.setAppSecret(weixinConfig.getSecret());

		*/
/**
		 * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
		 * 2：false采用明文模式，同时也支持混合模式
		 *//*

		ac.setEncryptMessage(_Config.p.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(_Config.p.get("encodingAesKey",
				"setting it in config file"));
		return ac;
	}
	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}


	public static void main(String[] args) {

		//System.out.println("111_222".split("_")[0]);
		BigDecimal n=new BigDecimal(4.9);
		System.out.println(n.intValue());
	}

}
*/
